window.RouterConfig = (() => {
    // 错误组件处理
    const ErrorComponent = (path) => ({
        name: `ErrorComponent_${path.replace(/\//g, '_')}`,
        template: `<div class="component-error">组件加载失败: ${path}</div>`
    });
    
    // 依赖组件错误处理
    const handleComponentError = (path) => (err) => {
        console.error(`依赖组件加载失败: ${path}`, err);
        return { default: ErrorComponent(path) };
    };
    
    // 主组件错误处理
    const handleMainComponentError = (err) => {
        console.error('主组件加载异常:', err);
        return {
            default: {
                name: 'GlobalErrorComponent',
                template: `
                    <div class="global-component-error">
                        <h3>页面加载失败</h3>
                        <p>错误原因：${err.message}</p>
                        <el-button @click="$router.go(0)">刷新页面</el-button>
                    </div>
                `,
                components: {}
            }
        };
    };
    
    const istest = window.APP_CONFIG.baseurl === 'https://zp.kzhgzs.cn/';
    // 全局依赖缓存池
    const dependencyCache = new Map();
    // 路径解析函数，接受当前组件路径作为基准
    const resolveComponentPath = (basePath, relativePath) => {
        const baseParts = basePath.split('/').filter(p => p);
        const relativeParts = relativePath.split('/').filter(p => p);
        let resolvedParts = [...baseParts.slice(0, -1)]; // 移除文件名，保留目录
        relativeParts.forEach(part => {
            if (part === '..') {
                if (resolvedParts.length > 0) resolvedParts.pop();
            } else if (part !== '.') {
                resolvedParts.push(part);
            }
        });
        const resolved = resolvedParts.join('/').replace(/^\/+/, '').replace(/\/+/g, '/');
        return resolved;
    };
    
    // 文件名提取器
    const getCacheKey = (filePath, version) => {
        const normalizedPath = filePath.replace(/\/+/g, '/').replace(/\?.*$/, '').replace(/\.\w+$/, ''); // 移除所有扩展名
        return `${normalizedPath}@v${version}`;
    };
    
    // 组件加载器（支持嵌套依赖路径解析）
    const componentLoader = (mainPath, dependencies = []) => {
        return async () => {
            const baseURL = window.APP_CONFIG.componentBase;
            const version = window.APP_CONFIG.demo == 'yes' ? window.APP_CONFIG.version : '1';
            const loadDependencies = async (deps, currentPath) => {
                return Promise.all(deps.map(async depPath => {
                    const resolvedPath = resolveComponentPath(currentPath, depPath);
                    const url = `${baseURL}/${resolvedPath}?v=${version}`;
                    const cacheKey = getCacheKey(resolvedPath, version);
                    if (dependencyCache.has(cacheKey)) {
                        if(istest) console.log(`[DEBUG] 使用缓存依赖:%c${cacheKey}`,'color: green;');
                        return dependencyCache.get(cacheKey);
                    }
                    const loadPromise = (async () => {
                        try {
                            if(istest) console.log(`[DEBUG] 加载依赖:%c${cacheKey}`,'color: red;');
                            const componentModule = await import(url);
                            // 递归加载子依赖
                            if (componentModule.default?.dependencies) {
                                const childDeps = await loadDependencies(componentModule.default.dependencies,resolvedPath);
                                componentModule.default.components = childDeps.reduce((acc, mod) => {
                                    if (mod?.default) acc[mod.default.name] = mod.default;
                                    return acc;
                                }, {});
                            }
                            return componentModule;
                        } catch (err) {
                            return handleComponentError(resolvedPath)(err);
                        }
                    })();
                    
                    dependencyCache.set(cacheKey, loadPromise);
                    return loadPromise;
                }));
            };
            // 主加载逻辑
            try {
                const mainDir = mainPath.split('/').slice(0, -1).join('/');
                const [depModules, mainModule] = await Promise.all([
                    loadDependencies(dependencies, mainDir),
                    (async () => {
                        const mainCacheKey = getCacheKey(mainPath, version);
                        if (dependencyCache.has(mainCacheKey)) {
                            if(istest) console.log(`[DEBUG] 使用缓存主组件:%c${mainCacheKey}`,'color: green;');
                            return dependencyCache.get(mainCacheKey);
                        } else {
                            if(istest) console.log(`[DEBUG] 加载主组件:%c${mainCacheKey}`,'color: red;');
                            const promise = import(`${baseURL}/${mainPath}?v=${version}`).catch(handleMainComponentError);
                            dependencyCache.set(mainCacheKey, promise);
                            return promise;
                        }
                    })()
                ]);
                mainModule.default.components = depModules.reduce((acc, mod) => {
                    if (mod?.default) acc[mod.default.name] = mod.default;
                    return acc;
                }, {});
                return mainModule;
            } catch (err) {
                return handleMainComponentError(err);
            }
        };
    };
    
    const defineRoutes = () => [
        {
            path: '/',
            name: 'home',
            meta: { title: '首页' },
            component: componentLoader('home/home.js')
        },
        {
            path: '/login',
            name: 'login',
            meta: { title: '用户登录' },
            component: componentLoader('home/login.js')
        },
        {
            path: '/cxtj',
            name: 'cxtj',
            meta: { title: '查询输入' },
            component: componentLoader('home/cxtj.js')
        },
        {
            path: '/cxjg',
            name: 'cxjg',
            meta: { title: '查询结果' },
            component: componentLoader('home/cxjg.js')
        },
        {
            path: '/submit-result',
            name: 'submitResult',
            meta: { title: query => query.type === 'reservation' ? '预约结果' : '提交结果'},
            component: componentLoader('home/SubmitResult.js')
        },
        {
            path: '/dblc',
            name: 'dblc',
            meta: { title: '多表联查' },
            component: componentLoader('home/dblc.js')
        },
        {
            path: '/form/:tableid/:rowid',
            name: 'formedit',
            meta: { title: '添加/修改数据' },
            component: componentLoader('home/rowform.js', ['../common/uniedit.js', '../common/UploadDialog.js']),
        },
        {
            path: '/applylist',
            name: 'applylist',
            meta: { title: '流程列表' },
            component: componentLoader('home/applylist.js'),
        },
        {
            path: '/mylist',
            name: 'mylist',
            component: componentLoader('home/mylist.js'),
        },
        {
            path: '/applyDetail/:id',
            name: 'applyDetail',
            meta: { title: '流程审批' },
            component: componentLoader('home/applyDetail.js'),
        },
        {
            path: '/bloglist',
            name: 'bloglist',
            meta: { title: '公告列表' },
            component: componentLoader('home/bloglist.js')
        },
        {
            path: '/blog/:id',
            name: 'blogview',
            meta: { title: '公告详情' },
            component: componentLoader('home/blogview.js')
        },
        {
            path: '/productList',
            name: 'productList',
            meta: { title: '商品列表' },
            component: componentLoader('home/productList.js')
        },
        {
            path: '/productview/:id',
            name: 'productview',
            meta: { title: '商品详情' },
            component: componentLoader('home/productview.js')
        },
    	{
            path: '/admin',
            meta: { title: '管理后台' },
            component: componentLoader('admin/Layout.js'),
            children: [{
                  path: '', // 空路径匹配/admin
                  name: 'admin',
                  meta: { title: '项目管理' },
                  redirect: {name: 'AdminBgsx'} // 重定向到bgsx子路由
                },
                {
                	path: 'bgsx',
                	name: 'AdminBgsx',
                	meta: { title: '项目管理' },
                	component: componentLoader('admin/bgsx.js', ['../common/bgsxform.js', '../common/readxlsx.js'])
                },
                {
                	path: 'table',
                	name: 'AdminTable',
                	meta: { title: '查看详细数据' },
                	component: componentLoader('admin/bgsxtable.js', ['../common/crudtable.js', '../common/exportxlsx.js', '../common/zjdr.js', '../common/filterform.js', '../common/printexcel.js', '../common/datafx.js'])
                },
                {
                	path: 'homediy',
                	name: 'AdminHomediy',
                	meta: { title: '首页diy' },
                	component: componentLoader('admin/template.js', ['../common/ComponentPreview.js', '../common/PropertyPanel.js'])
                },
                {
                	path: 'zsmb',
                	name: 'AdminZsmb',
                	meta: { title: '证书模板' },
                	component: componentLoader('admin/zsmb.js')
                },
                {
                	path: 'addzsmb',
                	name: 'AdminAddZsmb',
                	meta: { title: '编辑证书模板' },
                	component: componentLoader('admin/addzsmb.js', ['../common/zsmbfield.js'])
                },
                {
                	path: 'product',
                	name: 'AdminProduct',
                	meta: { title: '积分商城' },
                	component: componentLoader('admin/product.js', ['../common/kzhedit.js', '../common/imgpicker.js'])
                },
                {
                	path: 'purchaselist',
                	name: 'AdminPurchaseList',
                	meta: { title: '订单列表' },
                	component: componentLoader('admin/purchaseList.js')
                },
                {
                    path: 'user',
                    name: 'AdminUser',
                    meta: { title: '用户管理' },
                    component: componentLoader('admin/user.js'),
                },
                {
                    path: 'file',
                    name: 'AdminFile',
                    meta: { title: '文件管理' },
                    component: componentLoader('admin/file.js', ['../common/fileoperation.js', '../common/UploadDialog.js']),
                },
                {
                    path: 'permissions',
                    name: 'AdminPermissions',
                    meta: {title: '角色权限'},
                    component: componentLoader('admin/permissions.js'),
                },
                {
                    path: 'system',
                    name: 'AdminSystem',
                    meta: { title: '系统管理' },
                    component: componentLoader('admin/system.js', ['../common/upload.js'])
                },
                {
                    path: 'menus',
                    name: 'AdminMenus',
                    meta: { title: '菜单管理' },
                    component: componentLoader('admin/menus.js')
                },
                {
                    path: 'blog',
                    name: 'AdminBlog',
                    meta: { title: '公告管理' },
                    component: componentLoader('admin/blog.js')
                },
                {
                    path: 'addblog',
                    name: 'AdminAddBlog',
                    meta: { title: '编辑公告' },
                    component: componentLoader('admin/addblog.js', ['../common/kzhedit.js', '../common/imgpicker.js'])
                },
                {
                	path: 'wymb',
                	name: 'AdminWymb',
                	meta: { title: '网页模板' },
                	component: componentLoader('admin/wymb.js')
                },
                {
                	path: 'addwymb',
                	name: 'AdminAddWymb',
                	meta: { title: '编辑网页模板' },
                	component: componentLoader('admin/addwymb.js', ['../common/imgpicker.js'])
                },
                {
                    path: 'update',
                    name: 'Adminupdate',
                    meta: { title: '在线更新' },
                    component: componentLoader('admin/update.js')
                },
                {
                    path: 'help',
                    name: 'Adminhelp',
                    meta: { title: '使用帮助' },
                    component: componentLoader('admin/help.js')
                }
            ]
    	}
    ];
    let routerInstance = null;
    // 创建路由实例（修复函数调用）
    const createRouter = () => {
        if (routerInstance) return routerInstance; // 单例模式
        const routes = defineRoutes();
        // 收集所有路由的component加载函数
        const collectComponents = (routes) => {
            const components = [];
            const traverse = (routes) => {
                routes.forEach(route => {
                    if (route.component) {
                        components.push(route.component);
                    }
                    if (route.children) {
                        traverse(route.children);
                    }
                });
            };
            traverse(routes);
            return components;
        };
        const allComponents = collectComponents(routes);
        // 预加载组件函数
        const preloadComponents = () => {
            if(istest) console.log('[预加载] 开始预加载', allComponents.length);
            allComponents.forEach(component => {
                component().catch(err => {
                    console.error('预加载组件失败:', err);
                });
            });
        };
        preloadComponents(); // 预加载组件
        routerInstance = VueRouter.createRouter({
            history: VueRouter.createWebHashHistory(),
            routes
        });
        // 路由守卫
        routerInstance.beforeEach(async (to, from) => {
            try {
                const version = window.APP_CONFIG.demo == 'yes' ? window.APP_CONFIG.version : '1';
                if (to.path.startsWith('/admin')) {
                    await window.loadStyle(`admin.css?v=${version}`);
                } else {
                    await window.loadStyle(`index.css?v=${version}`);
                }
                // 等待浏览器一帧时间（确保CSSOM构建完成）
                await new Promise(resolve => requestAnimationFrame(resolve));
            } catch (err) {
                console.error('CSS加载失败:', err);
            }
            if (['admin','home','AdminBgsx'].includes(to.name)) {
                // 判断是否从首页进入admin，或者从admin进入首页
                const shouldHideCSS = (['login', 'home'].includes(from.name) && ['admin','AdminBgsx'].includes(to.name)) || (['login', 'admin'].includes(from.name)  && ['admin','AdminBgsx'].includes(to.name));
                if (shouldHideCSS) document.getElementById('app').classList.add('app-hidden'); // 使用 CSS 类隐藏
            }
        });
        routerInstance.afterEach(() => {
            document.getElementById('app').classList.remove('app-hidden');
        });
        return routerInstance;
    };
    
    createRouter();

	return {
		router: routerInstance,
		createRouter,
		componentLoader
	};
})();